<template>
  <div class="add-person-container">
    <div class="container">
      <div class="form-card">
        <div class="form-header">
          <button @click="goBack" class="back-button">
            <span>←</span>
          </button>
          <h1 class="form-title">添加人物</h1>
        </div>

        <form @submit.prevent="handleSubmit" class="person-form">
          <!-- 头像上传 -->
          <div class="form-group">
            <label class="form-label">头像</label>
            <div class="avatar-upload">
              <div class="avatar-preview" @click="triggerFileInput">
                <img v-if="formData.avatar" :src="formData.avatar" alt="头像预览">
                <div v-else class="avatar-placeholder">
                  <span class="upload-icon">📷</span>
                  <span class="upload-text">点击上传头像</span>
                </div>
              </div>
              <input 
                ref="fileInput" 
                type="file" 
                accept="image/*" 
                @change="handleFileChange"
                style="display: none"
              >
            </div>
          </div>

          <!-- 人物名称 -->
          <div class="form-group">
            <label class="form-label">人物名称 *</label>
            <input 
              v-model="formData.rankName" 
              type="text" 
              class="form-input"
              placeholder="请输入人物名称"
              required
            >
          </div>

          <!-- 排行榜分类 -->
          <div class="form-group">
            <label class="form-label">排行榜分类 *</label>
            <select v-model="formData.categoryId" class="form-select" required>
              <option value="">请选择分类</option>
              <option v-for="category in categories" :key="category.id" :value="category.id">
                {{ category.categoryName }}
              </option>
            </select>
          </div>

          <!-- 简介 -->
          <div class="form-group">
            <label class="form-label">简介</label>
            <textarea 
              v-model="formData.intro" 
              class="form-textarea"
              placeholder="请输入人物简介"
              rows="5"
            ></textarea>
          </div>

          <!-- 提交按钮 -->
          <div class="form-actions">
            <button type="button" @click="goBack" class="btn-cancel">取消</button>
            <button type="submit" class="btn-submit" :disabled="submitting">
              {{ submitting ? '提交中...' : '提交' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getRankingCategoryPage, createRankingPerson, uploadFile } from '@/api/forum'

const router = useRouter()
const fileInput = ref(null)
const submitting = ref(false)
const uploadedFile = ref(null)

// 表单数据
const formData = ref({
  avatar: '',
  rankName: '',
  categoryId: '',
  intro: '',
  status: 1
})

// 分类列表
const categories = ref([])

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await getRankingCategoryPage({
      pageNum: 1,
      pageSize: 100
    })
    if (response.code === 200 && response.data && response.data.list) {
      categories.value = response.data.list
    }
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value?.click()
}

// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0]
  if (file) {
    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      alert('请选择图片文件')
      return
    }
    
    // 验证文件大小（限制5MB）
    if (file.size > 5 * 1024 * 1024) {
      alert('图片大小不能超过5MB')
      return
    }

    // 保存文件对象用于上传
    uploadedFile.value = file

    // 预览图片
    const reader = new FileReader()
    reader.onload = (e) => {
      formData.value.avatar = e.target.result
    }
    reader.readAsDataURL(file)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (submitting.value) return

  // 验证必填项
  if (!formData.value.rankName.trim()) {
    alert('请输入人物名称')
    return
  }
  
  if (!formData.value.categoryId) {
    alert('请选择排行榜分类')
    return
  }

  try {
    submitting.value = true
    
    let avatarUrl = ''
    
    // 如果有上传文件，先上传图片
    if (uploadedFile.value) {
      console.log('开始上传图片...')
      const uploadResponse = await uploadFile(uploadedFile.value)
      console.log('上传响应:', uploadResponse)
      
      if (uploadResponse.code === 200) {
        // 处理不同的返回格式
        if (typeof uploadResponse.data === 'string') {
          avatarUrl = uploadResponse.data
        } else if (uploadResponse.msg && typeof uploadResponse.msg === 'string' && uploadResponse.msg.startsWith('http')) {
          // URL 在 msg 字段中
          avatarUrl = uploadResponse.msg
        } else if (uploadResponse.data && uploadResponse.data.url) {
          avatarUrl = uploadResponse.data.url
        } else if (uploadResponse.data && uploadResponse.data.path) {
          avatarUrl = uploadResponse.data.path
        }
        console.log('图片URL:', avatarUrl)
      }
    }
    
    // 构建提交数据
    const submitData = {
      avatar: avatarUrl,
      rankName: formData.value.rankName,
      categoryId: formData.value.categoryId,
      intro: formData.value.intro,
      status: 1
    }
    
    console.log('提交数据:', submitData)
    
    // 调用API提交数据
    const response = await createRankingPerson(submitData)
    console.log('创建响应:', response)
    
    if (response.code === 200) {
      alert('添加成功！')
      router.push('/ranking')
    } else {
      alert(response.msg || '添加失败，请稍后重试')
    }
  } catch (error) {
    console.error('提交失败:', error)
    alert('提交失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

// 返回
const goBack = () => {
  router.back()
}

onMounted(() => {
  fetchCategories()
})
</script>

<style scoped>
.add-person-container {
  padding: 20px 0;
  min-height: calc(100vh - 70px);
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

.form-card {
  background: white;
  border-radius: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  padding: 40px;
  max-width: 600px;
  margin: 0 auto;
}

.form-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  position: relative;
}

.back-button {
  position: absolute;
  left: 0;
  width: 40px;
  height: 40px;
  border: none;
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
  border-radius: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  color: #64748b;
  transition: all 0.3s ease;
}

.back-button:hover {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  transform: translateX(-4px);
}

.form-title {
  font-size: 2rem;
  font-weight: 800;
  text-align: center;
  flex: 1;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
}

.person-form {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-label {
  font-size: 0.95rem;
  font-weight: 600;
  color: #1e293b;
}

.avatar-upload {
  display: flex;
  justify-content: center;
}

.avatar-preview {
  width: 150px;
  height: 150px;
  border-radius: 16px;
  overflow: hidden;
  cursor: pointer;
  border: 3px dashed #cbd5e1;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-preview:hover {
  border-color: #667eea;
  transform: scale(1.05);
}

.avatar-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #94a3b8;
}

.upload-icon {
  font-size: 3rem;
}

.upload-text {
  font-size: 0.9rem;
}

.form-input,
.form-select,
.form-textarea {
  padding: 12px 16px;
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  font-size: 1rem;
  transition: all 0.3s ease;
  font-family: inherit;
}

.form-input:focus,
.form-select:focus,
.form-textarea:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-textarea {
  resize: vertical;
  min-height: 120px;
}

.form-actions {
  display: flex;
  gap: 16px;
  margin-top: 16px;
}

.btn-cancel,
.btn-submit {
  flex: 1;
  padding: 14px 24px;
  border: none;
  border-radius: 12px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-cancel {
  background: #f1f5f9;
  color: #64748b;
}

.btn-cancel:hover {
  background: #e2e8f0;
  transform: translateY(-2px);
}

.btn-submit {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.btn-submit:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.5);
}

.btn-submit:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .add-person-container {
    padding: 12px;
  }

  .form-card {
    padding: 24px 16px;
    border-radius: 16px;
  }

  .form-title {
    font-size: 1.5rem;
  }

  .back-button {
    width: 36px;
    height: 36px;
    font-size: 1.3rem;
  }

  .avatar-preview {
    width: 120px;
    height: 120px;
  }

  .upload-icon {
    font-size: 2.5rem;
  }

  .form-actions {
    flex-direction: column;
  }
}
</style>
